﻿using Microsoft.Extensions.Caching.Distributed;
using PHMEE.Admin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Volo.Abp.Guids;

namespace PHMEE.MqttClient.MqttBusinessCommand
{
    /// <summary>
    /// 采集器上传自诊断数据
    /// </summary>
    public class CheckDataCommand : BaseCommand
    {
        private IGuidGenerator _guidGenerator;
        private readonly RedisHelper _redisHelper;
        private ISensorRepository _sensorRepository;
        public CheckDataCommand(IGuidGenerator guidGenerator, RedisHelper redisHelper, ISensorRepository sensorRepository)
        {
            _guidGenerator = guidGenerator;
            _redisHelper = redisHelper;
            _sensorRepository = sensorRepository;
        }

        public override async Task ExecuteAsync(string requestInfo)
        {
            try
            {
                var checkDatas = JsonSerializer.Deserialize<List<CheckDataDto>>(requestInfo);
                if (checkDatas != null)
                {
                    ReturnData = new RetrunDto<List<CheckDataDto>>()
                    {
                        SN = SN,
                        MessageId = MessageId,
                        Data = checkDatas
                    };

                    //string json = JsonSerializer.Serialize(ReturnData, new JsonSerializerOptions { WriteIndented = true });
                    await _redisHelper.SetStringAsync($"PhmeeAdmin_Mqtt_CheckData_{SN}", SN, TimeSpan.FromMinutes(5));

                    // 保存到数据库
                    var sensors = checkDatas.Select(datas => new Sensor(_guidGenerator.Create())
                    {
                        CreateTIme = DateTime.UtcNow,
                        CollectCode = SN,
                        CheckType = datas.CheckType,
                        ChnoId = datas.Id,
                        CheckValue = datas.CheckValue,
                        State = datas.State
                    }).ToList();

                    //删除数据
                    await _sensorRepository.DeleteAsync(SN);
                    // 批量插入到数据库
                    await _sensorRepository.InsertManyAsync(sensors, autoSave: true);
                }

                isReplay = true;
            }
            catch (Exception)
            {
                Status = 0;
            }
        }
    }
}
